package com.jxb.test20241216;

import com.jxb.tree.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class BinTreePostOrderTraversal_145 {

    public static void main(String[] args) {

    }

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        accessTree(root, res);
        return res;
    }

    private void accessTree(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        accessTree(root.right,res);
        accessTree(root.left,res);
        res.add(root.val);
    }

    public List<Integer> postorderTraversalWithLoop(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode prevAccess = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            //         D
            //     B        C
            //   A    F   T   Y
            if (root.right == null || root.right == prevAccess) {
                res.add(root.val);
                prevAccess = root;//A->F
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }


    public List<Integer> postorderTraversalWithLoop1(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode preAccess = null;
        while (root != null || !stack.isEmpty()) {
            //将所有的左节点入栈
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == preAccess) {
                res.add(root.val);
                preAccess = root;
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }



}
